import path from 'path'
import Koa from 'koa'
import { koaBody } from 'koa-body' // 解析网络请求里的请求参数
import cors from 'koa2-cors' // 解决跨域问题
import parameter from 'koa-parameter' // 使用 koa-parameter 校验参数
import session from 'koa-session'
import koaStatic from 'koa-static'
import logger from 'koa-logger'
import router from '../route/index.ts'
import errHandler from './errHandler.ts'
import { __dirname } from '../utils/common.ts'
import ctxfun from './ctxfun.ts'
import seqErr from '../constant/seq.err.ts'

const app = new Koa()

for (const item of Object.keys(ctxfun)) {
  app.use((<any>ctxfun)[item])
}
app.use(seqErr)

app.use(
  cors({
    // 如果前端配置了withCredentials=true，后端设置Access- Control - Allow - Origin不能为 " * ", 而必须是你的源地址。
    origin: (ctx): any => {
      console.log(ctx.url)
      // 设置允许来自指定域名请求
      if (ctx.url.includes('/dev')) {
        return 'http://localhost:8081' // 只允许此域名的请求
      }
    },
    maxAge: 5, // 指定本次预检请求的有效期，单位为秒。
    credentials: true, // 是否允许发送Cookie
    allowMethods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'], // 设置所允许的HTTP请求方法
    allowHeaders: ['Content-Type', 'Authorization', 'Accept'], // 设置服务器支持的所有头信息字段
  }),
)

app.keys = [process.env.SESSION_SECREAT!] // session加密字段
const CONFIG = {
  key: 'koa.sess' /** (string) cookie key (default is koa.sess) */,
  /** (number || 'session') maxAge in ms (default is 1 days) */
  /** 'session' will result in a cookie that expires when session/browser is closed */
  /** Warning: If a session cookie is stolen, this cookie will never expire */
  maxAge: 15 * 60 * 1000,
  autoCommit: true /** (boolean) automatically commit headers (default true) */,
  overwrite: true /** (boolean) can overwrite or not (default true) */,
  httpOnly: true /** (boolean) httpOnly or not (default true) */,
  signed: true /** (boolean) signed or not (default true) */,
  rolling:
    false /** (boolean) Force a session identifier cookie to be set on every response. The expiration is reset to the original maxAge, resetting the expiration countdown. (default is false) */,
  renew:
    false /** (boolean) renew session when session is nearly expired, so we can always keep user logged in. (default is false)*/,
  // secure: true, /** (boolean) secure cookie*/
  sameSite:
    null /** (string) session cookie sameSite options (default null, don't set it) */,
}
app.use(session(<any>CONFIG, app))

app.use(logger())

app.use(
  koaBody({
    multipart: true,
    formidable: {
      uploadDir: path.join(__dirname(), '../upload'), // 上传目录
      keepExtensions: true, // 保留文件扩展名
      maxFields: 1000, // 字段的最大数量，默认为 1000
      maxFiles: 100, // 上传文件的最大数量，默认为 100
      minFileSize: 1, // 每个文件的最小大小，默认为 1 B
      maxFileSize: 200 * 1024 * 1024, // 每个文件的最大大小，默认为 200 MB
      maxFieldsSize: 2 * 1024 * 1024, // 表单字段（文件除外）的最大大小，默认为 2 MB
    },
    onError: (err, ctx) => {
      ctx.status = 400
      ctx.body = { error: err.message }
    },
  }),
)
app.use(parameter(app))
app.use(router.routes())
app.use(router.allowedMethods())
app.use(koaStatic(path.join(__dirname(), '../upload')))

// 捕捉错误
app.on('error', errHandler)

export default app
